/**
 * Created by user on 2015/10/27.
 */


var async = require('async');
var mysqlUtil = require('../../../common/utils/mysqlUtil');
var User = mongoose.model('user');
var Community = mongoose.model('community');
var Som = mongoose.model('system_operateMessages');
var Soml = mongoose.model('system_operateMessages_log');
var toolUtil = require('../../../common/utils/toolUtil');
var moment = require('moment');

exports.pushNoticeService = function (req, callback) {

    //logger.debug('3天不活跃客户');

    var body = req.body;
    var mode = body.mode;
    var type = body.type;

    logger.debug(body);

    switch(type)
    {
        case '1': //雷锋团成员
            User.count({userRole:3}, function (err, count) {
                var temp = [{ucount: count}];
                callback(err, temp);

            });
            break;
        case '2': //小区版主
            User.count({userRole:1}, function (err, count) {
                var temp = [{ucount: count}];
                callback(err, temp);

            });
            break;
        case '3'://7天内新注册用户
            var time = new Date(moment().add(-7, 'days').format("YYYY/MM/DD"));

            User.count({dateCreated :{$gte: time}}, function (err, count) {
                var temp = [{ucount: count}];
                callback(err, temp);
            });

            break;
        case '4'://3天未上线用户
            var sql = '';
            sql += 'select count(uid)ucount from (    ';
            sql += ' select uid, max(actiondate),count(actiondate),adddate(current_date, interval -3 day)';
            sql += ' from  66xiaoqu_rec.dau';
            sql += ' group by uid having max(actiondate)= adddate(current_date, interval -3 day)';
            sql += ')V';
            logger.debug(sql);
            mysqlUtil.queryBI(sql, function (err, result) {
                callback(err, result)
            });
            break;
        case '5'://7天未上线用户
            var sql = '';
            sql += 'select count(uid)ucount from (    ';
            sql += ' select uid, max(actiondate),count(actiondate),adddate(current_date, interval -7 day)';
            sql += ' from  66xiaoqu_rec.dau';
            sql += ' group by uid having max(actiondate)= adddate(current_date, interval -7 day)';
            sql += ')V';
            logger.debug(sql);
            mysqlUtil.queryBI(sql, function (err, result) {
                callback(err, result)
            });
            break;
        case '6'://2周未上线用户
            var sql = '';
            sql += 'select count(uid)ucount from (    ';
            sql += ' select uid, max(actiondate),count(actiondate),adddate(current_date, interval -14 day)';
            sql += ' from  66xiaoqu_rec.dau';
            sql += ' group by uid having max(actiondate)= adddate(current_date, interval -14 day)';
            sql += ')V';
            logger.debug(sql);
            mysqlUtil.queryBI(sql, function (err, result) {
                callback(err, result)
            });
            break;
        case '7'://导入用户
            break;
        case '8'://选择小区
            break;
        case '9'://省市用户
            break;

        case '10'://特定用户
            break;

        case '11'://大于4周未上线用户
            var sql = '';
            sql += 'select count(uid)ucount from (    ';
            sql += ' select uid, max(actiondate),count(actiondate),adddate(current_date, interval -28 day)';
            sql += ' from  66xiaoqu_rec.dau';
            sql += ' group by uid having max(actiondate)< adddate(current_date, interval -28 day)';
            sql += ')V';
            logger.debug(sql);
            mysqlUtil.queryBI(sql, function (err, result) {
                callback(err, result)
            });
            break;
        case '12': //完成一项新手任务的用户
            var sql = '';
            //sql += "select V.user,C.mobilePhone from ";
            //sql += "( ";
            sql += "	select  count(A.user)ucount from 66xiaoqu_rec.user_task A ";
            sql += "	inner join 66xiaoqu_rec.user_task_subTask B on A._id = B.user_task_id ";
            sql += "	where B.status = 'True' ";
            sql += "	group by A.user ";
            sql += "	having count(B.status)=1 ";
            //sql += " )V inner join 66xiaoqu_rec.user C on V.user = C._id ";

            break;
        case '13':
            var option = {};

            if (body.beginDate || body.endDate) {
                if (body.beginDate && body.endDate) {
                    //if (body.beginDate < body.endDate) {
                        option.dateCreated = {$gte: body.beginDate, $lte: body.endDate};
                    //};
                } else if (body.beginDate) {
                    option.dateCreated = {$gte: body.beginDate};
                } else if (body.endDate) {
                    option.dateCreated = {$lte: body.endDate};
                }
            }
            logger.debug(option);
            User.count(option, function (err, count) {
                var temp = [{ucount: count}];
                callback(err, temp);

            });
            break;
        default:

    }


};


exports.pushMessageService = function (req, callback) {

    //logger.debug('3天不活跃客户');

    var body = req.body;
    var mode = body.mode;
    var type = body.type;

    var ip = req.headers['X-Real-IP'];
    logger.debug(body);

    switch(type)
    {
        case '1': //雷锋团成员
            User.find({userRole:3}).exec(function (err, result) {
                if(result) {
                    switch (mode) {
                        case '1': //系统消息
                            exports.putMessageData(result,body,ip);
                            break;
                        case '2'://私信
                            exports.putLetterData(result,body);
                            break;
                        case '3':   //短信
                            exports.putSMSData(result,body);
                            break;
                        default :
                            callback(err, {});
                    }
                }
                callback(err, {});
            });
            break;
        case '2': //小区版主
            User.find({userRole:1}).exec(function (err, result) {
                if(result) {
                    switch (mode) {
                        case '1': //系统消息
                            exports.putMessageData(result,body,ip);
                            break;
                        case '2'://私信
                            exports.putLetterData(result,body);
                            break;
                        case '3':   //短信
                            exports.putSMSData(result,body);
                            break;
                        default :
                            callback(err, {});
                    }
                }
                callback(err, {});

            });
            break;
        case '3'://7天内新注册用户

            var time = new Date(moment().add(-7, 'days').format("YYYY/MM/DD"));

            User.find({dateCreated :{$gte: time}}).exec(function (err, result) {
                if(result) {
                    switch (mode) {
                        case '1': //系统消息
                            exports.putMessageData(result,body,ip);
                            break;
                        case '2'://私信
                            exports.putLetterData(result,body);
                            break;
                        case '3':   //短信
                            exports.putSMSData(result,body);
                            break;
                        default :
                            callback(err, {});
                    }
                }
                callback(err, {});
            });
            break;
        case '4'://3天未上线用户
            var sql = '';
            sql += 'select uid id,A.mobilePhone,A.huanxinUserName from (    ';
            sql += ' select uid, max(actiondate),count(actiondate),adddate(current_date, interval -3 day)';
            sql += ' from  66xiaoqu_rec.dau';
            sql += ' group by uid having max(actiondate)= adddate(current_date, interval -3 day)';
            sql += ')V join 66xiaoqu_rec.user A on V.uid = A._id';
            logger.debug(sql);
            mysqlUtil.queryBI(sql, function (err, result) {

                if(result) {
                    switch (mode) {
                        case '1': //系统消息
                            exports.putMessageData(result,body,ip);
                            break;
                        case '2'://私信
                            exports.putLetterData(result,body);
                            break;
                        case '3':   //短信
                            exports.putSMSData(result,body);
                            break;
                        default :
                            callback(err, {});
                    }
                }

                callback(err, {});
            });
            break;
        case '5'://7天未上线用户
            var sql = '';
            sql += 'select uid id,A.mobilePhone,A.huanxinUserName from (    ';
            sql += ' select uid, max(actiondate),count(actiondate),adddate(current_date, interval -7 day)';
            sql += ' from  66xiaoqu_rec.dau';
            sql += ' group by uid having max(actiondate)= adddate(current_date, interval -7 day)';
            sql += ')V join 66xiaoqu_rec.user A on V.uid = A._id';
            logger.debug(sql);
            mysqlUtil.queryBI(sql, function (err, result) {
                if(result) {
                    switch (mode) {
                        case '1': //系统消息
                            exports.putMessageData(result,body,ip);
                            break;
                        case '2'://私信
                            exports.putLetterData(result,body);
                            break;
                        case '3':   //短信
                            exports.putSMSData(result,body);
                            break;
                        default :
                            callback(err, {});
                    }
                }
                callback(err, {});
            });
            break;
        case '6'://2周未上线用户
            var sql = '';
            sql += 'select uid id,A.mobilePhone,A.huanxinUserName from (    ';
            sql += ' select uid, max(actiondate),count(actiondate),adddate(current_date, interval -14 day)';
            sql += ' from  66xiaoqu_rec.dau';
            sql += ' group by uid having max(actiondate)= adddate(current_date, interval -14 day)';
            sql += ')V join 66xiaoqu_rec.user A on V.uid = A._id';
            logger.debug(sql);
            mysqlUtil.queryBI(sql, function (err, result) {
                if(result) {
                    switch (mode) {
                        case '1': //系统消息
                            exports.putMessageData(result,body,ip);
                            break;
                        case '2'://私信
                            exports.putLetterData(result,body);
                            break;
                        case '3':   //短信
                            exports.putSMSData(result,body);
                            break;
                        default :
                            callback(err, {});
                    }
                }
                callback(err, {});
            });
            break;
        case '7'://导入用户
            break;
        case '8'://选择小区
            break;
        case '9'://省市用户
            break;
        case '10'://特定用户

            switch (mode) {
                case '1':   //系统消息
                    exports.putMessageData(body.uList,body,ip);
                    break;
                case '2':   //私信
                    User.find({_id:{$in:body.uList}},'_id huanxinUserName').exec(function (err, result) {
                        exports.putLetterData(result,body);
                    });
                    break;
                case '3':   //短信
                    exports.putSMSData(body.uList,body);
                    break;
                default :
                    callback(err, {});
            }
            break;

        case '11'://大于4周未上线用户
            var sql = '';
            sql += 'select uid id,A.mobilePhone,A.huanxinUserName from (    ';
            sql += ' select uid, max(actiondate),count(actiondate),adddate(current_date, interval -14 day)';
            sql += ' from  66xiaoqu_rec.dau';
            sql += ' group by uid having max(actiondate)< adddate(current_date, interval -28 day)';
            sql += ')V join 66xiaoqu_rec.user A on V.uid = A._id';
            logger.debug(sql);
            mysqlUtil.queryBI(sql, function (err, result) {
                if(result) {
                    switch (mode) {
                        case '1': //系统消息
                            exports.putMessageData(result,body,ip);
                            break;
                        case '2'://私信
                            exports.putLetterData(result,body);
                            break;
                        case '3':   //短信
                            exports.putSMSData(result,body);
                            break;
                        default :
                            callback(err, {});
                    }
                }
                callback(err, {});
            });
            break;
        case '12': //完成一项新手任务的用户
            var sql = '';
            sql += "select V.user,C.mobilePhone from ";
            sql += "( ";
            sql += "	select  A.user from 66xiaoqu_rec.user_task A ";
            sql += "	inner join 66xiaoqu_rec.user_task_subTask B on A._id = B.user_task_id ";
            sql += "	where B.status = 'True' ";
            sql += "	group by A.user ";
            sql += "	having count(B.status)=1 ";
            sql += " )V inner join 66xiaoqu_rec.user C on V.user = C._id ";

            break;

        case "13":

            var option = {};

            if (body.beginDate || body.endDate) {
                if (body.beginDate && body.endDate) {
                    //if (body.beginDate < body.endDate) {
                        option.dateCreated = {$gte: body.beginDate, $lte: body.endDate};
                    //};
                } else if (body.beginDate) {
                    option.dateCreated = {$gte: body.beginDate};
                } else if (body.endDate) {
                    option.dateCreated = {$lte: body.endDate};
                }
            }
            logger.debug(option);
            /*  宝宝树66小区二次改造    mod   luolh 注册用户私信不可修正 20170816   start   */
            // User.find(option,'_id').sort({'dateCreated':-1}).exec(function (err, result) {
            User.find(option,'_id huanxinUserName').sort({'dateCreated':-1}).exec(function (err, result) {
                /*  宝宝树66小区二次改造    mod   luolh 注册用户私信不可修正  20170816   end   */
                if(result) {
                    switch (mode) {
                        case '1': //系统消息
                            exports.putMessageData(result,body,ip);
                            break;
                        case '2'://私信
                            exports.putLetterData(result,body);
                            break;
                        case '3':   //短信
                            exports.putSMSData(result,body);
                            break;
                        default :
                            callback(err, {});
                    }
                }
                callback(err, {});
            });


            break;
        default:

    }
    callback(null,{});
};


exports.putMessageData = function (result,input,ip,pusthType) {
    //logger.debug(result);
    var userList = [];
    if(result && input.type != '10') {
        for (user in result) {
            if(result[user].id) {
                userList.push(result[user].id);
            }
        }
    }else if(result && input.type == '10'){
        userList = result;
    }
    logger.debug('input');
    logger.debug(input);
    //logger.debug(userList);
    redisClient.HGET('topicIdPool',input.contentId, function (err, res) {
        logger.debug(res);
        if (res) {
            input.contentId = res;
        }
        var content = {
            type: 1,
            flag: 2,
            openType: input.openType,
            contentId: input.contentId,
            //createdBy: input.createdBy,
            desc: input.message,
            url: input.url
        };

        var tasks = exports.releaseTasks(userList, 990);
        for (var count = 0; count < tasks.length; ++count) {
            var pushData = {
                uList: tasks[count],
                content: content,
                ip: ip,
                tag: input.tag,
                type: 'operate',
                msgType: 2
            };
            logger.debug('==========================Start '+count);
            //pushData.uList = tasks[count];
            //logger.debug(tasks[count]);
            toolUtil.putMessageGetuiPushMQ(pushData);
            //delete pushData.uList;
            logger.debug('==========================End   '+count);
        }
    });
};


exports.putLetterData = function (result,input){

    //var userList = [];
    //if(result) {
    //    for (user in result) {
    //        userList.push(result[user]._id);
    //    };
    //};

    var count = 0;

    var counter = 0;
    async.forEachSeries(result, function(user, callback) {
        // console.log("pushCustomerServiceMessage: ", user._id);
        toolUtil.pushCustomerServiceMessage(user, input.message);

        ++counter;

        if(++count == 30) {
            setTimeout(function () {
                console.log("pushed: ", counter);
                callback(null);
            }, 1000);
            count = 0;
        } else {
            callback(null);
        }
    }, function(err) {
        if (err)
            console.log("putLetterData: ", err);
        console.log("putLetterData: pushed", result.length);
    });
};


exports.putSMSData = function (result,input){

    var phoneList = '';
    if(result && input.type != '10') {
        for (var user in result) {
            phoneList += result[user].mobilePhone +',';
        }
    }else{

        phoneList = result;
    }
    logger.debug(phoneList);

    if (input.message && phoneList.length>0)  toolUtil.putMessageSMS(phoneList, input.message);


};



/***
 * 发布任务：分割成一个个小任务
 * 注：每个任务包含count个任务量
 * @param task 一个数组，包含所有数组
 * @param count
 */
exports.releaseTasks = function(task,count) {
    logger.debug("============================================"+new Date().getTime());
    var tasks = [];
    var taskCount;
    if(!count)
    {
        count = 1000;
    }
    if(task instanceof Array) {
        if(task.length>count)
        {
            taskCount = task.length/count;
            for (var startPosition=0 ;startPosition<taskCount;++startPosition)
            {
                if(startPosition === (taskCount-1))
                {
                    tasks.push(task.slice(startPosition*count,task.length));
                }
                else
                {
                    tasks.push(task.slice(startPosition*count,count*(startPosition+1)));
                }
            }
            logger.info("============================================"+new Date().getTime());
            return tasks;
        }
        else {
            tasks.push(task);
            return tasks;
        }
    }
    return task
};

exports.pushMessageListService = function (req, callback){

    var body = req.body;
    //logger.debug(body);
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    //var paged = (req.params.size && req.params.page);

    var option = body;
    //var sortType = paged ? {endDate:-1} : {};

    if (option.title) option.title = new RegExp(option.title);
    logger.debug(option);
    async.series([

        function (callbackInner) {
            Soml.count(option, function (err, count) {

                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, totalPage:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },
        function (callbackInner) {

            Soml.find(option).sort({dateCreated:-1}).skip(index).limit(size)
                .exec(function (err, results) {

                    if (err) {
                        callbackInner(err);
                    } else {

                        async.eachSeries(results, function (push, callbackInner2) {

                            var opt = {pushLogId:push._id.toString(),readFlag:true};
                            //logger.debug(opt);
                            Som.count(opt, function (err, count) {

                                push._doc.readCount = count;

                                //获取推送数和推送成功数
                                var key = "system_operate_message:contentId:" + push._id;
                                //logger.debug(key);
                                redisClient.HGETALL(key, function (err, res) {

                                    //logger.debug(res);
                                    if(res) {
                                        push._doc.targetPushCount = res.targetPushCount;
                                        push._doc.pushCount = res.pushCount;
                                        //logger.debug(push);
                                    }
                                    callbackInner2(err, push);
                                });
                                //callbackInner2(err, push);
                            });


                        }, function (err) {
                            callbackInner(err, results);
                        });

                        //callbackInner(null, results);
                    }
                });

        }], callback);

};